
from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
import re

# 接口分析：登陆接口是一个反序列化逻辑，需要校验username和password
class LoginSerializer(serializers.Serializer):

    username = serializers.CharField(max_length=20, label='用户名')
    password = serializers.CharField(min_length=8,max_length=20, label='密码')

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        # 格式校验
        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$', password):
            raise serializers.ValidationError('密码有误')

        # 用户名和密码的业务校验
        user = authenticate(username=username, password=password)
        if user is None:
            raise serializers.ValidationError('用户名或密码错误')

        # TODO: 签发token
        # jwt_payload_handler函数传入用户模型类对象，生成载荷信息
        payload = jwt_payload_handler(user)
        # jwt_encode_handler函数传入载荷信息，生成token值
        token = jwt_encode_handler(payload)

        # 把token值和user对象作为有效数据返回
        return {
            'token': token,
            'user': user
        }